<?php


namespace app\admin\controller;



use think\App;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;
class PermissionController extends CommonController
{
    private static $PERMISSION_TABLE="permission";
    private static $PERMISSION_ROLE_TABLE="permission_role";
    use ResponseJson;

    public function __construct(App $app = null)
    {
        parent::__construct($app);

    }

    public function addPermission(Request $request){
         $res=$request->param();
         $rule = [
            'name'  => 'require|max:10',
            'info'   => 'require|max:20',
        ];
         $message  = [
            'name.require' => '权限名称必填',
            'name.max' => '权限名称最多10个字符',
            'info.require'=> '权限简介必填',
            'info.max' => '权限简介最多20个字符',
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($res);
        if(!$result) {
          return $this->jsonResponse(-1,$validate->getError(),'');
        }

        if(!$request->param('pid')){
            $res['pid']=0;
        }
        $is_set=Db::table(self::$PERMISSION_TABLE)
            ->where('name','=',$res['name'])
            ->where('delete_flag','=',0)
            ->find();
        if ($is_set){
            return $this->jsonResponse(-1,'权限名称重复','');
        }

        try {
            Db::startTrans();
            $res['created_by']=$this->getUserId($request->header('token'));
            $res['created_time']=date("Y-m-d H:i:s",time());
            Db::table(self::$PERMISSION_TABLE)
                ->insert($res);
            Db::commit();
            return $this->SuccessResponse('添加成功','');
        }catch (Exception $e){
            Db::rollback();
            return $this->jsonResponse(-1,$e->getMessage(),'');
        }

    }

    public function getPermission(Request $request){
        $page=$request->get('page')?$request->get('page'):self::$Page;
        $limit=$request->get('limit')?$request->get('limit'):self::$Limit;
       $res= Db::table(self::$PERMISSION_TABLE)
            ->alias('a')
            ->where(function ($query)use($request){
                $query->where('a.delete_flag','=',0);
                if ($request->get('val')!=null||!empty($request->get('val'))){
                    $query->where('a.name','like','%'.$request->get('val').'%');
                }
            })
            ->field('a.id,a.name,a.info,a.route,a.status,a.is_show,a.pid,a.title,a.icon,a.menu_path,a.menu_name,a.component')
            ->fieldRaw('(select b.name from permission as b where b.delete_flag = 0 and b.status= 0 and b.id = a.pid) as p_name')
           ->limit($limit)
           ->page($page)
           ->select();
       $total= Db::table(self::$PERMISSION_TABLE)->where('delete_flag','=',0)->count();
       $fenye=['limit'=>$limit,'page'=>$page,'total'=>$total];
       $data=['res'=>$res,'fenye'=>$fenye];
        return $this->SuccessResponse('success',$data);
    }

    public function getPermissionOption(){
       $res= Db::table(self::$PERMISSION_TABLE)
            ->where('delete_flag','=',0)
            ->where('status','=',0)
            ->field('id,name')
            ->select();
       return $this->SuccessResponse('success',$res);
    }

    public function CheckPermissionShow(Request $request){
        if (!$request->get('id')){
            return $this->jsonResponse(-1,'缺少参数','');
        }
        $is_show=$request->get('is_show')==1?1:0;
        try {
            Db::table(self::$PERMISSION_TABLE)->where('id','=',$request->get('id'))->update(['is_show'=>$is_show,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            return $this->SuccessResponse('更新成功','');
        }catch (Exception $e){
            return $this->jsonResponse(-1,$e->getMessage(),'');
        }
    }

    public function CheckPermissionStatus(Request $request){
        if (!$request->get('id')){
            return $this->jsonResponse(-1,'缺少参数','');
        }
        $status=$request->get('status')==1?1:0;
        try {
            Db::table(self::$PERMISSION_TABLE)->where('id','=',$request->get('id'))->update(['status'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            return $this->SuccessResponse('更新成功','');
        }catch (Exception $e){
            return $this->jsonResponse(-1,$e->getMessage(),'');
        }
    }

    public function updatePermission(Request $request){
        $res=$request->param();
        $rule = [
            'name'  => 'require|max:10',
            'info'   => 'require|max:20',
        ];
        $message  = [
            'name.require' => '权限名称必填',
            'name.max' => '权限名称最多10个字符',
            'info.require'=> '权限简介必填',
            'info.max' => '权限简介最多20个字符',
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($res);
        if(!$result) {
            return $this->jsonResponse(-1,$validate->getError(),'');
        }

        if(!$request->param('pid')){
            $res['pid']=0;
        }
        $is_set=Db::table(self::$PERMISSION_TABLE)
            ->where('name','=',$res['name'])
            ->where('delete_flag','=',0)
            ->where('id','<>',$request->get('id'))
            ->find();
        if ($is_set){
            return $this->jsonResponse(-1,'权限名称重复','');
        }
        unset($res['p_name']);
        try{
            Db::startTrans();
            $res['update_by']=0;
            $res['update_time']=date("Y-m-d H:i:s",time());
            Db::table(self::$PERMISSION_TABLE)
                ->where('id','=',$request->get('id'))
                ->update($res);
            Db::commit();
            return $this->SuccessResponse('更新成功','');
        }catch (Exception $e){
            Db::rollback();
            return $this->jsonResponse(-1,$e->getMessage(),'');
        }
    }

    public function deletePermission(Request $request){
       if (!$request->get('id')){
           return $this->jsonResponse(-1,'参数错误','');
       }
        try {
           Db::startTrans();
           //删除权限表
            Db::table(self::$PERMISSION_TABLE)->where('id','=',$request->get('id'))->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date("Y-m-d H:i:s",time())]);
            Db::table(self::$PERMISSION_TABLE)->where('pid','=',$request->get('id'))->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date("Y-m-d H:i:s",time())]);
            //删除角色权限表
            Db::table(self::$PERMISSION_ROLE_TABLE)->where('permission_id','=',$request->get('id'))->update(['delete_flag'=>1,'update_by'=>0,'update_time'=>date("Y-m-d H:i:s",time())]);
            $child_permission=Db::table(self::$PERMISSION_TABLE)->where('pid','=',$request->get('id'))->select();
            foreach ($child_permission as $k => $item) {
                Db::table(self::$PERMISSION_ROLE_TABLE)->where('id','=',$item['id'])->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date("Y-m-d H:i:s",time())]);
            }
            Db::commit();
            return $this->SuccessResponse('删除成功','');

        }catch (Exception $e){
           Db::rollback();
           return $this->jsonResponse(-1,$e->getMessage(),'');
        }
    }

    //获取树状权限
    public function GetPermissionTree(){
        $res= DB::table(self::$PERMISSION_TABLE)
            ->where('delete_flag','=','0')
            ->where('status','=','0')
            ->field('id,name,info,pid,route')
            ->select();
        $list=$this->GetTree($res);
        return $this->SuccessResponse('success',$list);
    }

    private function GetTree($data,$pid = 0){
        $child = [];   // 定义存储子级数据数组
        foreach ($data as $key => $value) {
            if ($value['pid'] == $pid) {
                unset($data[$key]);  // 使用过后可以销毁
                $value['child'] = $this->GetTree($data,$value['id']);   // 递归调用，查找当前数据的子级
                $child[] = $value;   // 把子级数据添加进数组
            }
        }
        return $child;
    }

}